package com.rayboo.example.java8;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Stream Collectors 示例
 *
 * @author ray
 * @since 2019/07/29
 *
 * <p>收集器是扩展Object类的最终类。
 *
 * <p>https://beginnersbook.com/2017/10/java-8-stream-collectors-class-with-examples/
 */
public class StreamCollectorsExample {

    public static void main(String[] args) {

        System.out.println("===== Java8 – Stream Collectors groupingBy and counting Example =====");

        List<String> names = Arrays.asList("Jon", "Ajeet", "Steve", "Ajeet", "Jon", "Ajeet");
        Map<String, Long> map = names.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(map);

        class Student{
            int id;
            String name;
            int age;

            public Student(int id, String name, int age) {
                this.id = id;
                this.name = name;
                this.age = age;
            }
        }
        List<Student> students = new ArrayList<Student>();
        //Adding Students
        students.add(new Student(11,"Jon",22));
        students.add(new Student(22,"Steve",18));
        students.add(new Student(33,"Lucy",22));
        students.add(new Student(44,"Sansa",23));
        students.add(new Student(55,"Maggie",18));

        System.out.println("===== Java8 – Stream Collectors example of fetching data as List =====");

        //Fetching student names as List
        List<String> stuNames = students.stream().map(n->n.name).collect(Collectors.toList());
        System.out.println(stuNames);

        System.out.println("===== Java8 –  Collecting Data as Set =====");

        //Fetching student data as a Set
        Set<Student> studentSet = students.stream()
                .filter(n-> n.id>22)
                .collect(Collectors.toSet());
        //Iterating Set
        for(Student stu : studentSet) {
            System.out.println(stu.id+" "+stu.name+" "+stu.age);
        }


        System.out.println("===== Getting the average age of students using averagingInt() method =====");

        //Getting the average Age
        Double avgAge = students.stream().collect(Collectors.averagingInt(s->s.age));
        System.out.println("Average Age of Students is: "+avgAge);
    }
}
